package com.example.easyutils.garbagepage;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.easyutils.BaseActivity;
import com.example.easyutils.R;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.util.DialogLoad;
import com.example.easyutils.util.MyTypeAdapter;
import com.example.easyutils.util.StringAndBitmap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class Main extends BaseActivity {
    private LinearLayout ll_root;
    private float rotateDu = 0;
    private EditText searchView;
    private DialogLoad dialogLoad;
    private TextView showRubbish,detailMsg;
    private ImageView rubbishImage;
    private GridView rubbishGrid;
//    private Dialog dialog;
    private SimpleAdapter simpleAdapter;
    private int[] rubbishInt = new int[]{
            R.drawable.rubbish_recircle,
            R.drawable.rubbish_kitchen,
            R.drawable.rubbish_other,
            R.drawable.rubbish_danger
    };
    private String[] rubbish_str = new String[]{"可回收垃圾","厨余垃圾","其他垃圾","有害垃圾"};
    private static final int GET_RUBBISH_CODE = 1,GET_RUBBISH_ERROR_CODE = 2;

    private Map rubbishSelectMap;
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            dialogLoad.dialogCancel();
            switch (msg.what){
                case GET_RUBBISH_CODE:
                    String codeStr = rubbishSelectMap.get("code").toString();
                    if(!codeStr.equals("1")) {
                        showRubbish.setText(rubbishSelectMap.get("msg").toString());
                        Toast.makeText(Main.this,rubbishSelectMap.get("msg").toString(),Toast.LENGTH_LONG).show();
                        return;
                    }
                    Map rubbishMap = new HashMap();
                    rubbishMap = (Map) rubbishSelectMap.get("data");
                    showRubbish.setText(rubbishMap.get("title").toString()+"--"+rubbishSelectMap.get("msg").toString());
                    detailMsg.setText(rubbishMap.get("desc").toString());
                    Glide
                            .with(Main.this)
                            .load(rubbishMap.get("pic").toString())
                            .into(rubbishImage);
                    final String img = rubbishMap.get("pic").toString();
                    rubbishImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            show(img);
//                dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                        }
                    });

//                    OnSet();

                    break;
                case GET_RUBBISH_ERROR_CODE:
                        showRubbish.setText("出错啦");
                    dialogLoad.dialogCancel();
                        break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.garbage_activity);
        searchView = (EditText)findViewById(R.id.search_garbage);
        showRubbish = (TextView)findViewById(R.id.query_rubbish);
        detailMsg = (TextView)findViewById(R.id.detailMsg);
        rubbishImage = (ImageView)findViewById(R.id.rubisshImage);
        ll_root = (LinearLayout)findViewById(R.id.search_layout);




        dialogLoad = new DialogLoad(Main.this);


//        rubbishGrid = (GridView)findViewById(R.id.grid_rubbish);


        List rubbishList = new ArrayList();
        for(int i = 0; i < rubbish_str.length; i ++){
            Map map = new HashMap<>();
            map.put("rubbishName",rubbish_str[i]);
            map.put("rubbishImg", rubbishInt[i]);
            rubbishList.add(map);
        }

    }

    private void show(String img) {
        Log.d("img",img);
        Dialog dialog = new Dialog(this);
        //去掉标题线
        dialog.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_photo);
        ImageView imageView = (ImageView)dialog.findViewById(R.id.large_image);
        StringAndBitmap stringAndBitmap = new StringAndBitmap();
        imageView.setImageBitmap(stringAndBitmap.stringToBitmap(img));
        //背景透明
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.show();

        dialog.setCanceledOnTouchOutside(true); // Sets whether this dialog is
        Window w = dialog.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.x = 0;
        lp.y = 40;
        dialog.onWindowAttributesChanged(lp);

//        Window window = dialog.getWindow();
//        WindowManager.LayoutParams lp = window.getAttributes();
//        lp.gravity = Gravity.CENTER; // 居中位置
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        window.setAttributes(lp);
//        window.setWindowAnimations(R.style.AppTheme);  //添加动画
    }

    public void queryGarbage(View v){
        Log.d("searchData",searchView.getText()+"");
        String query = searchView.getText().toString();
        switchRubbish(query);
    }

    /**
     * 组合动画
     *
     *
     */
//    public void OnSet() {
//        float height = ll_root.getHeight();
//        ObjectAnimator objectAnimatorRotate = ObjectAnimator.ofFloat(showRubbish, "rotation", rotateDu, 360);
//        ObjectAnimator objectAnimatorTr = ObjectAnimator.ofFloat(showRubbish, "translationY", height, height / 2, height / 3, height / 4, height / 5, height / 6);
//        AnimatorSet animatorSet = new AnimatorSet();
//        animatorSet.setDuration(2000);
//        animatorSet.play(objectAnimatorRotate).with(objectAnimatorTr);
//        animatorSet.start();
//    }

    public void switchRubbish(String query){//垃圾分类接口
//        http://api.63code.com/garbage/api.php?keyword=
        dialogLoad.dialogLoaded("加载中...");
        HttpGetRequest.sendOkHttpGetRequst("https://api.oioweb.cn/api/aigarbage.php?key="+query,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(GET_RUBBISH_ERROR_CODE);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("垃圾分类：",responseData);
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,List>>(){

                        }.getType());

                        rubbishSelectMap = dataDetail;
                        handler.sendEmptyMessage(GET_RUBBISH_CODE);

                    }
                });
    }
}
